package com.ambercrm.tools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import com.ambercrm.business.UpGradeActivity;
import com.ambercrm.common.Common;
import com.ambercrm.constant.UrlConstant;
import com.ambercrm.http.HttpUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

public class UpGradeUtils {
    public static void checkUpgrade(final Context context) {
        checkUpgrade(context, false);
    }

    /**
     * @param context
     * @param isUser 是否是用户手动触发升级
     */
    public static void checkUpgrade(final Context context, final boolean isUser) {
        AndPermission.with(context)
                .runtime()
                .permission(new String[] {Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE})
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        if (data.size() >= 1) {
                            HashMap<String, Object> map = new HashMap<>();
                            HashMap<String, Object> appdto = new HashMap<>();
                            appdto.put("serviceIP", "CRMApp");
                            appdto.put("version", UpGradeUtils.getVersionCode(context));
                            appdto.put("objectGroup", "安卓");
                            map.put("appdto", appdto);
                            HttpUtils.httpPost(UrlConstant.UPGRADE_URL, map, new HttpUtils.OnResponseListener() {
                                @Override
                                public void onSucceed(String result, int what) {
                                    try {
                                        JSONObject obj = new JSONObject(result);
                                        JSONObject resultObj = obj.getJSONObject("result");
                                        int versionCode = resultObj.getInt("version");
                                        if (versionCode > getVersionCode(context)) {
                                            String resourceUrl = resultObj.optString("resourceUrl");
                                            String resourceId = resultObj.optString("resourcesId");
                                            String mark = resultObj.getString("mark");
                                            int isForce = resultObj.getInt("forceUpdate");
                                            String apkUrl = resourceUrl + "/" + resourceId + "?token="+ Common.getInstance().getToken();
                                            Bundle b = new Bundle();
                                            b.putString("mark", mark);
//                                                b.putString("versionName", versionName);
                                            b.putString("apkUrl", apkUrl);
                                            b.putInt("isForce", isForce);
                                            Intent it = new Intent(context, UpGradeActivity.class);
                                            it.putExtras(b);
                                            context.startActivity(it);
                                        }
                                        else {
                                            if (isUser) {
                                                ToastUtils.showToast("当前已是最新版本");
                                            }
                                        }
                                    }
                                    catch (Exception e) {

                                    }
                                }

                                @Override
                                public void onFailed(String result, int what) {

                                }

                                @Override
                                public void onFinish(int what) {

                                }
                            }, 0);
                        }
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {

                    }
                })
                .start();
    }

    // 获取版本号
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo;
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    // 获取版本名
    public static String getVersionName(Context context) {

        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo;
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
            versionName = versionName.replace("v", "").replace("V", "");
            if (versionName.contains("_")) {
                versionName = versionName.split("_")[0];
            }
        } catch (Exception e) {
            versionName = "1.0.0";
        }

        return versionName;
    }

    // 8.0以上系统调用安装应用
    public static void startInstallApk(Activity context, String apkName) {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            if (!hasInstallPermission) {
                //注意这个是8.0新API
                Uri packageURI = Uri.parse("package:" + context.getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                context.startActivityForResult(intent, 100);
            }
            else {
                installApk(context, apkName);
            }
        }
        else {
            installApk(context, apkName);
        }
    }

    // 8.0以下系统安装应用
    public static void installApk(Activity context, String apkName) {
        FileUtils mFileUtils = new FileUtils();
        Uri mUri;
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        //7.0系统开始认为直接使用本地Uri是不安全的 所以以FileProvider共享给外部提高安全性
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", mFileUtils.getApksFile(apkName));
        } else {
            mUri = Uri.fromFile(mFileUtils.getApksFile(apkName));
        }
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(mUri,
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
